package com.by.yz.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.by.yz.R;
import com.by.yz.activity.base.BaseActivity;
import com.by.yz.adapter.GridAdapter;
import com.by.yz.common.MFGT;
import com.by.yz.custom.MyGridView;
import com.by.yz.entity.BingMing;
import com.by.yz.entity.GuiZeKu;
import com.by.yz.entity.JuTiZhengXiang;
import com.by.yz.entity.ZhengXiangMing;
import com.by.yz.loginUtil.DiagnosisRESTFul;
import com.by.yz.util.ToJSonObject;
import com.google.gson.Gson;
import com.hyphenate.easeui.widget.EaseAlertDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by pengpeng on 2017/4/15.
 */
public class diagnosis_zhengxiang extends BaseActivity  implements View.OnClickListener  {
    TextView zxm,allName,zxmNum;
    TextView zhengxiangList;
    TextView zxTishi;
    RelativeLayout zhengxiangLayout,zhengxingLayout;
    Button last,next,finish;
    private static List<String> zxmName;
    private static List<String> zxmNameHistory;
    private Spinner jtzx = null;
    private ArrayAdapter<CharSequence> adapterJtzx = null;
    private static List<String> jtzxList;
    private static String[] jtzxInfo;
    private static List<String> zhengxiang;
    String bingMing="";
    String jtzxm="";
    String juti="";
    String DoctorName="";
    String zhengxing="";
    String zx="";
    String bm="";
    private int num;
    private static GridAdapter adapter;
    private static List<Map<String,Object>> list;
    private MyGridView gv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diagnosis_zhengxiang);
        setToolbarTitle("选择症象");
        num = 0;
        initView();
        initDatas();
    }

    void initView(){
        zxTishi = (TextView)findViewById(R.id.zhengxing);
        zxm = (TextView)findViewById(R.id.zxmName);
        zxmNum = (TextView)findViewById(R.id.zxmNum);
        allName = (TextView)findViewById(R.id.allName);
        zhengxiangLayout = (RelativeLayout)findViewById(R.id.zhengxiangLayout);
        zhengxingLayout = (RelativeLayout)findViewById(R.id.zhengxingLayout);
        zhengxiangList = (TextView)findViewById(R.id.zhengxiangList);
        last = (Button)findViewById(R.id.last);
        last.setOnClickListener(this);
        next = (Button)findViewById(R.id.next);
        next.setOnClickListener(this);
        finish = (Button)findViewById(R.id.finish);
        finish.setOnClickListener(this);
        jtzx = (Spinner) super.findViewById(R.id.spinner);
        bingMing = getIntent().getStringExtra("BingMing");
        try {
            bm = URLDecoder.decode(bingMing, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        gv = (MyGridView)findViewById(R.id.zhengxingList2);
        DoctorName = getIntent().getStringExtra("DoctorName");
        zxmName =new ArrayList<String>();
        zxmNameHistory =new ArrayList<String>();
        jtzxList = new ArrayList<String>();
        jtzxInfo = new String[]{};
        zhengxiang = new ArrayList<String>();
    }

    void initDatas(){
        if(zhengxiang!=null && zhengxiang.size()!=0){
            Gson gson = new Gson();
            String str = gson.toJson(zhengxiang);
            zhengxiangLayout.setVisibility(View.VISIBLE);
            zhengxiangList.setText(str);
            zhengxingLayout.setVisibility(View.VISIBLE);
        }
        if(zxmName != null && !zxmName.isEmpty()){
            show();
        }else{
            zxmName.clear();
            DiagnosisRESTFul bmREST=new DiagnosisRESTFul();
            bmREST.getZhengXiangMing(bingMing,new DiagnosisRESTFul.MyGetCallBack(){
                @Override
                public void ok(JSONArray response) throws JSONException {
                    ZhengXiangMing zxm;
                    for(int i=0;i<response.length();i++){
                        JSONObject jsonObject= response.getJSONObject(i);
                        zxm= ToJSonObject.jsonToBean(jsonObject.toString(),ZhengXiangMing.class);
                        zxmName.add(i,zxm.getZxmName());
                    }
                    allName.setText("您选择的 【 "+bm+ " 】有以下症象名：");
                    for(int i=0;i<=zxmName.size()-1;i++){
                        String before = allName.getText().toString();
                        String add = zxmName.get(i);
                        allName.setText(before+(i+1)+"、"+add+"；");
                    }
//                    for(int i=zxmName.size()-1;i>=0;i--){
//                        String before = allName.getText().toString();
//                        String add = zxmName.get(i);
//                        int j = zxmName.size()-i;
//                        allName.setText(before+(j)+"、"+add+"；");
//                    }
                    String before1 = allName.getText().toString();
                    allName.setText(before1+"请按顺序选择对应症象");
                    Log.e("zxmName = ",zxmName.toString());
                    show();
                }
                @Override
                public void error(String error) {
                    Log.e("hj","更新失败"+error);
                }
            });
        }
    }

    void show(){
        if(num != 0){
            last.setClickable(true);
            last.setBackgroundColor(Color.rgb(72,206,85));
            last.setTextColor(Color.WHITE);
        }else{// 第一个选项没有上一步
            last.setClickable(false);
            last.setBackgroundColor(Color.GRAY);
            last.setTextColor(Color.BLACK);
        }
        if (zxmName.size()==1){
            hasFinish();
        }else{
            hasNext();
        }
//        for(int i=zxmName.size()-1;i>=0&&i>zxmName.size()-2;i--){
//            zxmNum.setText((num+1)+"、");
//            zxm.setText(zxmName.get(i));
//        }
        zxmNum.setText((num+1)+"、");
        zxm.setText(zxmName.get(0));
        jtzxm=zxm.getText().toString();
        try {
            juti = URLEncoder.encode(jtzxm,"Utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        DiagnosisRESTFul bmREST=new DiagnosisRESTFul();
        bmREST.jtZhengXiangMing(juti,bingMing,new DiagnosisRESTFul.MyGetCallBack(){
            @Override
            public void ok(JSONArray response) throws JSONException {
                jtzxList.clear();
                jtzxList.add(0,"请选择"+jtzxm);
                JuTiZhengXiang jtzx;
                int a = 1;
                for(int i=0;i<response.length();i++){
                    JSONObject jsonObject= response.getJSONObject(i);
                    jtzx= ToJSonObject.jsonToBean(jsonObject.toString(),JuTiZhengXiang.class);
                    jtzxList.add(a++,jtzx.getJtZhengXiang());
                }
                jtzxInfo = jtzxList.toArray(new String[jtzxList.size()]);
                handler.sendEmptyMessage(0);
            }
            @Override
            public void error(String error) {
                Log.e("hj","更新失败"+error);
            }
        });
    }

    void showList(){
        if(zhengxiang.size()==0){
            zhengxiangList.setVisibility(View.GONE);
        }else{
            zhengxiangList.setVisibility(View.VISIBLE);
            Gson gson = new Gson();
            String str = gson.toJson(zhengxiang);
            zhengxiangLayout.setVisibility(View.VISIBLE);
            zhengxiangList.setText(str);
            JSONArray data = new JSONArray();
            try{
                data = new JSONArray(str);
            }catch (JSONException e){
                Log.e("JSONException",e.toString());
            }finally {
                Log.e("data",data.toString());
                DiagnosisRESTFul bmREST=new DiagnosisRESTFul();
                bmREST.FindZhengXing(data, DoctorName, bingMing, new DiagnosisRESTFul.MyGetCallBack(){
                    @Override
                    public void ok(JSONArray response) throws JSONException {
                        if(response.length()>0){
                            zxTishi.setText("智能诊断得出如下症型:（点击查看详情）");
                            if(response.length() == 1){
                                hasFinish();
                            }else{
                                hasNext();
                            }
                            zhengxingLayout.setVisibility(View.VISIBLE);
                            gv.setVisibility(View.VISIBLE);
                            try{
                                list = new ArrayList<Map<String,Object>>();
                                Map<String,Object> map = null;
                                for(int i=0;i<response.length();i++){
                                    GuiZeKu gzk;
                                    JSONObject jsonObject = response.getJSONObject(i);
                                    gzk = ToJSonObject.jsonToBean(jsonObject.toString(), GuiZeKu.class);
                                    zx = gzk.getZhengxingName();
                                    map = new HashMap<String,Object>();
                                    map.put("text", gzk.getZhengxingName());
                                    map.put("bingming", bingMing);
                                    map.put("Type", 4);
                                    list.add(map);
                                }
                            }catch(Exception e){
                                Log.e("Exception = ",e.toString());
                            }finally{
                                bindGrid();
                            }
                        }else{
//                            zxTishi.setText("后台没有对应数据");
                            new EaseAlertDialog(diagnosis_zhengxiang.this, "该数据采集中").show();
                            next.setClickable(false);
                            next.setBackgroundColor(Color.GRAY);
                            next.setTextColor(Color.BLACK);
                            finish.setClickable(false);
                            finish.setBackgroundColor(Color.GRAY);
                            finish.setTextColor(Color.BLACK);
                            gv.setVisibility(View.GONE);
                        }
                    }
                    @Override
                    public void error(String error) {
                        Log.e("FindZhengXing.error = ",error);
                    }
                });
            }
        }
    }

    private void bindGrid(){
        adapter = new GridAdapter(this, list);
        gv.setAdapter(adapter);
    }

    void hasFinish(){
        next.setClickable(false);
        next.setBackgroundColor(Color.GRAY);
        next.setTextColor(Color.BLACK);
        finish.setClickable(true);
        finish.setBackgroundColor(Color.rgb(72,206,85));
        finish.setTextColor(Color.WHITE);
    }

    void hasNext(){
        next.setClickable(true);
        next.setBackgroundColor(Color.rgb(72,206,85));
        next.setTextColor(Color.WHITE);
        finish.setClickable(false);
        finish.setBackgroundColor(Color.GRAY);
        finish.setTextColor(Color.BLACK);
    }

    protected Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    initJtzxAdapter();
                    break;
                default:
                    break;
            }
        }
    };

    private void initJtzxAdapter() {
        try {
            this.adapterJtzx = new ArrayAdapter<CharSequence>(this,
                    android.R.layout.simple_spinner_dropdown_item, jtzxInfo);
            this.jtzx.setAdapter(adapterJtzx);

            this.jtzx.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {//选择item的选择点击监听事件
                public void onItemSelected(AdapterView<?> arg0, View arg1,
                                           int arg2, long arg3) {
                    // TODO Auto-generated method stub
                    if(!zhengxiang.isEmpty()) {
                        if(num < zhengxiang.size())
                         Log.e("上一步选择的是",zhengxiang.get(num));
                    }
                    Log.e("您选择的是",adapterJtzx.getItem(arg2).toString());
                    Log.e(" num == ",num+"");
//                    Log.e("zhengxiang.size(0) ==",zhengxiang.size()+"");
                    if(zhengxiang.size() == 0 || zhengxiang.size() <= num){
                        zhengxiang.add(num,"");
                    }
                    if(adapterJtzx.getItem(arg2).toString().indexOf("请选择") == -1 ) {
//                        zhengxiang.set(zhengxiang.size()-1, jtzxm + ":" + adapterJtzx.getItem(arg2).toString());
                        zhengxiang.set(zhengxiang.size()-1,  adapterJtzx.getItem(arg2).toString());
                    }else{
                        zhengxiang.set(zhengxiang.size()-1,"");
                        zhengxiang.remove(zhengxiang.size()-1);
                    }
//                    Log.e("zhengxiang.size(1) ==",zhengxiang.size()+"");
                    showList();
                }
                public void onNothingSelected(AdapterView<?> arg0) {
                    // TODO Auto-generated method stub
                    Log.e("Nothing","Nothing");
                }
            });

            int k= adapterJtzx.getCount();
            if(num < zhengxiang.size()){
                String imagepath = zhengxiang.get(num);
                for(int i=0;i<k;i++){
                    if(this.adapterJtzx.getItem(i).toString().equals(imagepath)){
                        this.jtzx.setSelection(i,true);// 默认选中项
//                        zhengxiang.set(zhengxiang.size()-1, jtzxm + ":" + adapterJtzx.getItem(i).toString());
                        zhengxiang.set(zhengxiang.size()-1,  adapterJtzx.getItem(i).toString());
                        showList();
                        break;
                    }
                }
            }

        }catch (Exception e){}finally {}
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.last:
                num--;
                Log.e("上一步前","--------------------");
                Log.e("zxmName",zxmName.toString());
                Log.e("zxmNameHistory",zxmNameHistory.toString());
                //在zxmName[]第一位置插入数据
                zxmName.add(zxmName.size(),zxmName.get(zxmName.size()-1));
                for(int i=zxmName.size()-1;i>=1;i--){
                    zxmName.set(i,zxmName.get(i-1));
                }
                zxmName.set(0,zxmNameHistory.get(num));
                //在zxmName[]第一位置插入数据
                zxmNameHistory.remove(num);
                if(zhengxiang.size() > num+1){
                    zhengxiang.remove(zhengxiang.size()-1);
                }
                Log.e("上一步后","--------------------");
                Log.e("zxmName",zxmName.toString());
                Log.e("zxmNameHistory",zxmNameHistory.toString());
                initDatas();
                break;
            case R.id.next:
                if(jtzx.getSelectedItem().toString().equals("请选择"+jtzxm)){
                    final MaterialDialog registerSuccess = new MaterialDialog.Builder(diagnosis_zhengxiang.this)
                            .content("请选择"+jtzxm)
                            .show();
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        public void run() {
                            registerSuccess.dismiss();
                        }
                    }, 1000);
                }else{
                    Log.e("下一步前","--------------------");
                    Log.e("zxmName",zxmName.toString());
                    Log.e("zxmNameHistory",zxmNameHistory.toString());
                    zxmNameHistory.add(num,zxmName.get(0));
                    //删除zxmName[]第一个数据
                    for(int i = 0;i < zxmName.size()-1;i++){
                        zxmName.set(i,zxmName.get(i+1));
                    }
                    zxmName.remove(zxmName.size()-1);
                    //删除zxmName[]第一个数据
                    num++;
                    Log.e("下一步后","--------------------");
                    Log.e("zxmName",zxmName.toString());
                    Log.e("zxmNameHistory",zxmNameHistory.toString());
                    initDatas();
                }
                break;
            case R.id.finish:
                Context context = v.getContext();
                Intent intent = new Intent(context, diagnosis_result.class);
                intent.putExtra("ZhengXing",zx);
                intent.putExtra("BingMing",bingMing);
                context.startActivity(intent);
                break;
        }
    }
}